/****************
 *@description: 宠币账户 myPocket/coinsAccount/index
 *@author: Xhd
 *@API: 纪浩然
 *@date: 2023-11-28 19:38:50
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "../../../components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import VideoPlayer from "@/components/VideoPlayer";
import { getDateTime3 } from '@/utils/getDate';
import { apiGetWebMemberCoinRecordPage,apiGetWebMemberCoinRecordList } from '@/request/coinsAccount';
import store from "@/store/store";
import _ from 'lodash';
import {Space, Modal, Input, message} from "antd";
import Json2Excel from '@/utils/Json2Excel'

const { TextArea } = Input;

class CoinsAccount extends Component {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: "会员ID",
          dataIndex: "memberId",
          key: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        // {
        //   title: "实名姓名",
        //   dataIndex: "name",
        //   key: "name",
        // },
        {
          title: "会员手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        },
        {
          title: "会员状态",
          dataIndex: "memberStatus",
          key: "memberStatus",
          render: (text, render) => {
            let txt = ''
            switch (text) {
              case "Y":
                txt = '正常'
                break;
              case "N":
                txt = '冻结'
                break;
              default:
                break;
            }
            return txt;
          },
        },
        {
          title: "支出统计",
          dataIndex: "expendPrice",
          key: "expendPrice",
          render: (text) => {
            return (Number(text) /100).toString()
          }
        },
        {
          title: "收入统计",
          dataIndex: "incomePrice",
          key: "incomePrice",
          render: (text) => {
            return (Number(text) /100).toString()
          }
        },
        {
          title: "现有宠币数量",
          dataIndex: "coinBalance",
          key: "coinBalance",
          render: (text) => {
            return (Number(text) /10).toString()
          }
        },
        {
          title: "宠币账户状态",
          dataIndex: "coinAccountStatusContent",
          key: "coinAccountStatusContent",
          // render: (text, record) => {
          //   let txt = ''
          //   switch (text) {
          //     case 0:
          //       txt = '正常'
          //       break;
          //     case 1:
          //       txt = '封禁'
          //       break;
          //     default:
          //       break;
          //   }
          //   return txt;
          // }
        },
        {
          title: "操作",
          fixed: "right",
          width: 200,
          render: (text, render) => {
            return (
              <div>
                <TheButton haspermi={["myPocket:coinsAccount:accountDetail"]} onClick={() => this.goAccountDetail(render.memberId)}>详情</TheButton>
                <TheButton haspermi={["myPocket:coinsAccount:detail"]} onClick={() => this.goDetail(render.memberId)}>明细</TheButton>
              </div>
            );
          },
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      form_show: true,
      searchOption: [
        {
          field: 'memberData',
          label: '会员信息',
          placeholder: '输入会员ID/会员昵称/会员手机号',
          required: false,
          rules: [],
          type: 'Input',
          defaultValue: ''
        },
        {
          field: 'coinAccountStatus',
          label: '宠币账户状态',
          placeholder: '请选择',
          required: false,
          rules: [],
          type: 'Select',
          options: [{ value: 0, label: '正常' }, { value: 1, label: '封禁' }],
          defaultValue: ''
        },
        {
          field: 'currentCoins',
          label: '现有宠币数量',
          placeholder: '请输入',
          required: false,
          rules: [],
          type: 'NumRange',
          otherConfig: {
            precision: 1,
            max: 9999999.9,
            min: 0,
            minPlaceholder: '请输入最小宠币数量',
            maxPlaceholder: '请输入最大宠币数量'
          },
          minKey: 'currentCoinsStart',
          maxKey: 'currentCoinsEnd',
        },
      ],
      queryForm: {},
      stopReason: '',
      isvideoModalVisible: false,
      videoAddress: "",
      exportLoading: false
    };
  }

  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName === 'myPocketCoinsAccount') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      this.getData()
    }
  };

  // 获取表格数据
  getData = async (values) => {
    let { pageNo, pageSize } = this.state.pageData
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      let { ...form } = { ...this.state.queryForm }
      const params = {
        pageNo,
        pageSize,
        queryForm: { ...form }
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'myPocketCoinsAccount',
          ...params
        }
      })
      form.currentCoinsStart *= 10
      form.currentCoinsEnd *= 10
      let res = await apiGetWebMemberCoinRecordPage({
        pageNo,
        pageSize,
        ...form,
      })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
    })
  };

  goDetail = (id) => {
    this.props.history.push(`/myPocket/coinsAccount/detail/${id}`);
  };
  goAccountDetail = (id) => {
    this.props.history.push(`/myPocket/coinsAccount/accountDetail/${id}`,);
  };

  videoOk = async () => {
    this.setState({
      isvideoModalVisible: false,
      videoAddress: ""
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };

  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  onFormSearch(values) {
    let min = _.isNil(values.currentCoinsStart) && _.isEmpty(values.currentCoinsStart);
    let max = _.isNil(values.currentCoinsEnd) && _.isEmpty(values.currentCoinsEnd);
    if (min && !max){
      message.warning('请输入最小宠币数量')
    }
    else if (max && !min){
      message.warning('请输入最大宠币数量')
    }
    else {
      this.setState({
        pageData: { pageNo: 1, pageSize: 10 }
      }, () => {
        this.getData(values)
      })
    }
  }

  /**
   * @desc 表格数据导出
   * */
  toExport = async () => {
    const {queryForm} = this.state
    if (_.isEmpty(queryForm)) {
      Modal.warning({title: '请选择筛选条件并查询后再导出，暂不支持全量导出。',});
      return
    }
    else if (queryForm.currentCoinsStart === undefined && queryForm.currentCoinsEnd === undefined){
      Modal.warning({title: '请先输入现有宠币数量区间',});
      return
    }
    this.setState({exportLoading: true});
    queryForm.currentCoinsStart *= 10
    queryForm.currentCoinsEnd *= 10
    let res = await apiGetWebMemberCoinRecordList({
      ...queryForm,
    })
    if (res.code === 0) {
      let tB_data = res.data.map((item, index) => {
        return {
          ...item,
          index: index + 1,
          memberMobile: item.memberMobile.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'),
          memberStatus: item.memberStatus === 'Y' ? '正常' : '冻结',
          expendPrice: React.$transNum(item.expendPrice || 0, 2, -2),
          incomePrice: React.$transNum(item.incomePrice || 0, 2, -2),
          coinBalance: React.$transNum(item.coinBalance || 0, 1, -1),
        };
      });
      const option = {
        header: [
            {prop: "memberId", title: "会员ID", valueType: 'n'},
            {prop: "nickName", title: "用户昵称"},
            {prop: "memberMobile", title: "会员手机号"},
            {prop: "memberStatus", title: "会员状态"},
            {prop: "expendPrice", title: "支出统计", valueType: 'n'},
            {prop: "incomePrice", title: "收入统计", valueType: 'n'},
            {prop: "coinBalance", title: "现有宠币数量", valueType: 'n'},
            {prop: "coinAccountStatusContent", title: "宠币账户状态"},
        ],
        dataSource: tB_data,
        fileName: '用户宠币账户列表'
      }
      this.setState({exportLoading: false});
      Json2Excel(option)
    } else {
      React.$message({
        type: "warning",
        content: "导出操作失败,请重试",
      });
      this.setState({exportLoading: false});
    }
  }

  render() {
    const { exportLoading, columns, dataSource, pageData: { pageNo, pageSize }, total, searchOption, form_show, isvideoModalVisible, videoAddress } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton
              haspermi={['myPocket:coinsAccount:export']}
              size="middle"
              onClick={() => this.toExport()}
              type="default"
              loading={exportLoading}
          >
            导出
          </TheButton>
        </TheQueryForm>
        用户宠币账户列表
        <TheTable
          columns={columns}
          dataSource={dataSource}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        {isvideoModalVisible ?
          <Modal visible={isvideoModalVisible} onOk={this.videoOk} onCancel={this.videoOk}>
            <VideoPlayer src={videoAddress} />
          </Modal> : null}
      </div>
    );
  }
}

export default CoinsAccount;
